<template>
  <div class="home-page">
    <div class="home-header">
      <el-button
        type="primary"
        :disabled="recording"
        size="small"
        @click="handleStartRecording"
      >
        {{ recording ? "录制中..." : "开始录制" }}</el-button
      >
      <el-button
        type="primary"
        :disabled="!recording"
        size="small"
        @click="handleEndRecording"
        >结束录制</el-button
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import { onMounted, ref } from "vue";
const recording = ref(false);
let mediaRecorder: MediaRecorder | null = null;
let recordedChunks: Blob[] = [];
// 开启录制功能
const handleStartRecording = async () => {
  const source = await window.electronAPI.getScreenSource();
  console.log("获取到屏幕源：", source);

  const stream = await (navigator.mediaDevices as any).getUserMedia({
    audio: false,
    video: {
      mandatory: {
        chromeMediaSource: "desktop",
        chromeMediaSourceId: source.id,
      },
    },
  });

  mediaRecorder = new MediaRecorder(stream, {
    mimeType: "video/webm; codecs=vp9",
  });

  mediaRecorder.ondataavailable = (event) => {
    if (event.data.size > 0) recordedChunks.push(event.data);
  };

  mediaRecorder.onstop = async () => {
    const blob = new Blob(recordedChunks, { type: "video/webm" });
    const arrayBuffer = await blob.arrayBuffer(); // 👈 传 ArrayBuffer 而不是 Buffer
    window.electronAPI.saveVideo(arrayBuffer); // 👈 交给 preload 处理 Buffer
    recordedChunks = [];
  };

  mediaRecorder.start();
  recording.value = true;
};
// 结束录制功能
const handleEndRecording = () => {
  mediaRecorder?.stop();
  recording.value = false;
};
onMounted(() => {
  window.electronAPI.onSaveSuccess((filePath: string) => {
    ElMessage({
      message: `视频已保存到: ${filePath}`,
      type: "success",
    });
  });
});
</script>

<style scoped>
.home-page {
  width: 100vw;
  height: 100vh;
}
.home-header {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
}
</style>
